//
//  VWPlayerBasicControlLayer.swift
//  VideoPlayer_Example
//
//  Created by JY_NEW on 2021/10/13.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import ijkPlayerManager
import UIKit
import BasicExtensions

class VWPlayerBasicControlLayer: VWPlayerAutoDeactiveLayer {
    /// 倍速
    var speedAction: (() -> Void)?
    
    override var category: VideoPlayerLayerCategory { return .control }
    
    override var isDeactiveForTapBlank: Bool {
        return false
    }
    
    override func loadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.singleTap.addTarget( self, action: #selector(self.onTap))
        manager.observer.doubleTap.addTarget( self, action: #selector(self.onPlayOrPause))
        manager.observer.controlLocked.addTarget( self, action: #selector(self.onLockChanged))
    }
    override func unloadManager(_ manager: VideoPlayerLayerManagerType) {
        manager.observer.singleTap.removeTarget(self)
        manager.observer.doubleTap.removeTarget(self)
        manager.observer.controlLocked.removeTarget(self)
    }
    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.fullScreen.addTarget( self, action: #selector(self.onFullScreenChanged))
        player.observer.status.addTarget( self, action: #selector(self.onStatusChanged))
        player.observer.duration.addTarget( self, action: #selector(self.onDurationChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        player.observer.fullScreen.removeTarget(self)
        player.observer.status.removeTarget(self)
        player.observer.duration.removeTarget(self)
    }
    
    override func loadContainerView(_ containerView: UIView) {
        containerView.add {
            self.leftMargin.layout(.left, .marginY)
            self.lockButton.layout(.rightLeft(25), .centerY)
        }
        containerView.add(self.rightMargin, layout: .right, .marginY)
        containerView.add(self.topView, layout: .top, .marginX)
        containerView.add(self.bottomView, layout: .bottom, .marginX)
        
        self.topContentView.applyLayout(for: self.leftMargin, .leftRight)
        self.topContentView.applyLayout(for: self.rightMargin, .rightLeft)
        self.bottomContentView.applyLayout(for: self.leftMargin, .leftRight)
        self.bottomContentView.applyLayout(for: self.rightMargin, .rightLeft)
        
        self.onFullScreenChanged()
        self.onLockChanged()
    }
    
    @objc func onTap() {
        if self.status.isActived {
            self.deactive()
        }else{
            self.active()
        }
    }
    @objc func onFullScreenChanged() {
        let isFullScreen = self.playerManager?.isFullScreen ?? false
        UIView.performWithoutAnimation {
            self.bottomPortraitView.isHidden = isFullScreen
            self.bottomLandscapeView.isHidden = !isFullScreen
            self.lockButton.isHidden = !isFullScreen
        }
        
        let safeArea = isFullScreen ? UIView.safeArea : .zero
        self.topMargin.applyLayout(.update(.height(safeArea.top)))
        self.leftMargin.applyLayout(.update(.width(safeArea.left / 2)))
        self.rightMargin.applyLayout(.update(.width(safeArea.right / 2)))
        self.bottomMargin.applyLayout(.update(.height(safeArea.bottom)))
        // 非全屏解锁
        if !isFullScreen {
            self.manager?.isControlLocked = false
        }
    }
    @objc func onLockChanged() {
        let isLock = self.manager?.isControlLocked ?? false
        self.topView.isHidden = isLock
        self.bottomView.isHidden = isLock
        self.lockButton.isSelected = isLock
    }
    @objc func onStatusChanged() {
        self.portraitPlayButton.isSelected = self.playerManager?.status.isPlaying ?? false
        self.landscapePlayButton.isSelected = self.portraitPlayButton.isSelected
        self.landscapeNextButton.isHidden = !(self.context?.hasNext ?? false)
        self.loadDisplay()
    }
    func onCurrentTimeChanged() {
        if let player = self.playerManager {
            let timeStr = timeString(player.currentTime)
            self.portraitCurrentTimeLabel.text = timeStr
            self.portraitProgressView.value = Float(player.currentTime)
            self.landscapeCurrentTimeLabel.text = timeStr
            self.landscapeProgressView.value = Float(player.currentTime)
        }
    }
    @objc func onDurationChanged() {
        if let player = self.playerManager {
            let endTime = player.duration == 0 ? player.playableDuration : player.duration
            let timeStr = timeString(endTime)
            self.portraitEndTimeLabel.text = timeStr
            self.portraitProgressView.maximumValue = Float(endTime)
            self.landscapeEndTimeLabel.text = timeStr
            self.landscapeProgressView.maximumValue = Float(endTime)
            self.onCurrentTimeChanged()
        }
    }
    
    override func show(completion:@escaping () -> Void) {
        self.willShow()
        self.loadDisplay()
        self.aniamteShow(for: self.topView, from: .top, completion: nil)
        self.aniamteShow(for: self.lockButton, from: .left, completion: nil)
        self.aniamteShow(for: self.bottomView, from: .bottom, completion: completion)
        self.onCurrentTimeChanged()
        self.onFullScreenChanged()
    }
    override func hide(completion:@escaping () -> Void) {
        self.willHide()
        self.aniamteHide(for: self.topView, to: .top, completion: nil)
        self.aniamteHide(for: self.lockButton, to: .left, completion: nil)
        self.aniamteHide(for: self.bottomView, to: .bottom, completion: completion)
        self.onCurrentTimeChanged()
    }
    
    func loadDisplay() {
        self.titleLabel.text = self.context?.title
        self.landscapeNextButton.isHidden = !(self.context?.hasNext ?? false)
    }
    
    // MARK: 界面控件
    
    /// 四个边距
    lazy var topMargin: UIView = UIView(.height(0))
    lazy var leftMargin: UIView = UIView(.width(0))
    lazy var rightMargin: UIView = UIView(.width(0))
    lazy var bottomMargin: UIView = UIView(.height(0))
    
    /// 上面控件
    lazy var topView: UIView = {
        let top = UIView()
        
        top.add(UIImageView(.image("vw_player_top_bg")), layout: .margin)
        top.add {
            self.topMargin.layout(.top, .marginX)
            self.topContentView.layout(.bottomTop)
                .layout(for: .parent, .bottom)
        }
        return top
    }()
    
    /// 上面内容控件，统一放在一起，好跟状态栏拉距离的时候只拉一个
    lazy var topContentView: UIView = {
        let top = UIView(.height(44))
        
        let back = UIButton(.image(.init(named: "vw_common_back_button")), .size(49), .event(self, #selector(self.onBack)))
        
        top.add {
            back.layout(.left, .centerY)
            titleLabel.layout(.rightLeft, .centerY)
        }
        return top
    }()
    
    /// 上面内容控件，统一放在一起，好跟状态栏拉距离的时候只拉一个
    lazy var titleLabel: UILabel = UILabel(.text("我是标题"), .font(.pingfang(medium: 12)), .color(.white))
    
    /// 下面控件
    lazy var bottomView: UIView = {
        let bottom = UIView()
        
        bottom.add(UIImageView(.image(.init(named: "vw_player_bottom_bg"))), layout: .margin)
        bottom.add {
            self.bottomContentView.layout(.top)
            self.bottomMargin.layout(.bottomTop)
                .layout(for: .parent, .marginX, .bottom)
        }
        
        return bottom
    }()
    
    lazy var bottomContentView: UIStackView = {
        let stack = UIStackView(.axis(.vertical), .alignment(.fill), .distribution(.fill))
        
        stack.addArrangedSubview(self.bottomLandscapeView)
        stack.addArrangedSubview(self.bottomPortraitView)
        
        self.timer.addBlock { [weak self] in
            self?.onCurrentTimeChanged()
        }
        
        return stack
    }()
    
    /// 竖屏时下面控件
    lazy var bottomPortraitView: UIView = {
        let view = UIView(.height(44))
        
        let fullScreen = UIButton(.image(.init(named: "vw_player_fullscreen")), .width(44), .event(self, #selector(self.onFullScreenClick)))
        
        view.add {
            self.portraitPlayButton.layout(.left, .marginY)
            self.portraitCurrentTimeLabel.layout(.rightLeft(4), .centerY)
            self.portraitProgressView.layout(.rightLeft(8), .centerY)
            self.portraitEndTimeLabel.layout(.rightLeft(8), .centerY)
            fullScreen.layout(.rightLeft(4))
                .layout(for:.parent, .right, .marginY)
        }
        return view
    }()
    
    /// 竖屏播放按钮
    lazy var portraitPlayButton: UIButton = {
        return UIButton(.image(.init(named:"vw_player_start")),.image(.init(named:"vw_player_pause"), for: .selected), .width(44), .event(self, #selector(self.onPlayOrPause)))
    }()
    
    /// 竖屏当前时间
    lazy var portraitCurrentTimeLabel: UILabel = {
        return UILabel(.text("00:00"), .font(.pingfang(medium: 10)), .color(.white))
    }()
    
    /// 竖屏总时间
    lazy var portraitEndTimeLabel: UILabel = {
       return UILabel(.text("00:00"), .font(.pingfang(medium: 10)), .color(.white))
    }()
    
    /// 竖屏进度条
    lazy var portraitProgressView: UISlider = self.craeteProgressView()
    
    /// 横屏时下面控件
    lazy var bottomLandscapeView: UIView = {
        let view = UIView(.height(70))
        
        let top = UIView()
        
        top.add {
            self.landscapeCurrentTimeLabel.layout(.left(10), .centerY)
            self.landscapeProgressView.layout(.rightLeft(8), .centerY)
            self.landscapeEndTimeLabel.layout(.rightLeft(8), .centerY)
                .layout(for:.parent, .right(10))
        }
        let bottom = UIView(.height(40))
        
        let left = UIStackView(.axis(.horizontal), .alignment(.center), .distribution(.fill))
        
        let space = UIView(.size(10))
        
        left.addArrangedSubview(self.landscapePlayButton)
        left.addArrangedSubview(self.landscapeNextButton)
        
        bottom.add(left, layout: .left, .marginY)
        
        let right = UIStackView(.axis(.horizontal), .alignment(.fill), .distribution(.fill))
        
        right.addArrangedSubview(self.landscapeSpeedButton)
        
        bottom.add(right, layout: .right, .marginY)
        
        view.add {
            top.layout(.top, .marginX)
            bottom.layout(.bottomTop)
                .layout(for: .parent, .marginX, .bottom)
        }
        return view
    }()
    
    /// 横屏播放按钮
    lazy var landscapePlayButton: UIButton = {
        return UIButton(.image(.init(named:"vw_player_start")),.image(.init(named:"vw_player_pause"), for: .selected), .size(44), .event(self, #selector(self.onPlayOrPause)))
    }()
    
    /// 横屏下一集按钮
    lazy var landscapeNextButton: UIButton = {
        return UIButton(.image(.init(named: "vw_player_next")), .size(44), .event(self, #selector(self.onPlayNextClick)))
    }()
    
    /// 横屏倍速按钮
    lazy var landscapeSpeedButton: UIButton = {
        return UIButton(.text("倍速"), .font(.pingfang(medium: 14)), .color(.white), .width(60), .event(self, #selector(self.onSpeedClick)))
    }()
    
    /// 横屏当前时间
    lazy var landscapeCurrentTimeLabel: UILabel = {
       return UILabel(.text("00:00"), .font(.pingfang(medium: 10)), .color(.white))
    }()
    
    /// 横屏总时间
    lazy var landscapeEndTimeLabel: UILabel = {
       return UILabel(.text("00:00"), .font(.pingfang(medium: 10)), .color(.white))
    }()
    
    /// 横屏进度条
    lazy var landscapeProgressView: UISlider = self.craeteProgressView()
    
    /// 锁屏按钮
    lazy var lockButton: UIButton = {
        return UIButton(.image(.init(named: "vw_player_unlock")),.image(.init(named: "vw_player_lock"), for: .selected), .size(44), .event(self, #selector(self.onLockClick)))
    }()
    
    func craeteProgressView() -> UISlider {
        let progress = FXSlider(.lowPriority())
        let leftImage = UIImage.create(color: .systemBlue, size: [1000, 1.2])
        let rightImage = UIImage.create(color: .white, size: [1000, 1.2])
        let thumbImage = UIImage.create(color: .systemBlue, size: 12).byClip(corner: 6)
        progress.setMinimumTrackImage(leftImage, for: .normal)
        progress.setMaximumTrackImage(rightImage, for: .normal)
        progress.setThumbImage(thumbImage, for: .normal)
        progress.minimumValue = 0
        progress.addTarget(self, action: #selector(self.onProgressValueChanged(_:)), for: [.touchUpInside, .touchUpOutside])
        return progress
    }
    
    @objc func onBack() {
        if let player = self.playerManager {
            if player.isFullScreen {
                player.isFullScreen = false
            }else{
                self.delegate?.onPlayerQuit()
            }
        }
    }
    @objc func onPlayOrPause() {
        if let player = self.playerManager, self.isAllowControl {
            if player.status.isPlaying {
                player.pause()
            }else{
                player.play()
            }
        }
    }
    @objc func onPlayNextClick() {
        self.delegate?.onPlayerNext()
        self.loadDisplay()
    }
    @objc func onProgressValueChanged(_ slider: UISlider) {
        self.playerManager?.seek(to: TimeInterval(slider.value), completion: nil)
    }
    @objc func onFullScreenClick() {
        self.playerManager?.isFullScreen = true
    }
    @objc func onSpeedClick() {
        self.speedAction?()
    }
    @objc func onLockClick() {
        let isLock = !self.lockButton.isSelected
        self.lockButton.isSelected = isLock
        self.manager?.isControlLocked = isLock
    }
}
